﻿define(["jquery", "utils", "underscore", "template"], function ($, utils, _, template) {
    var loadArr = [];
    function gEl(el) {
        var s1 = ".";
        var s2 = "#";
        if (typeof el == 'string') {
            if (el.indexOf(s1) > -1 || el.indexOf(s2) > -1) {
                return $(el);
            } else {
                if ($(s1 + el).get(0)) {
                    return $(s1 + el);
                } else {
                    return $(s2 + el);
                }
            }
        } else {
            return $(el);
        }
    }

    function load() {
        return layer.open({
            type: 2,
            shadeClose: false
            //content: '加载测试中…',
        });
    }

    // 替换原生态alert
    function _alert(msg) {
        layer.open({
            content: msg,
            style: 'background-color:#e50012; color:#fff; border:none;text-align:center;',
            time: 3,
            shadeClose: false
        });
    }

    function dialog(opts) {
        var index = 1;
        layer.open({
            content: opts.msg,
            btn: opts.btns,
            shadeClose: false,
            yes: function () {
                if (index == 1) {
                    index++;
                    if (typeof opts.yes == 'function') {
                        opts.yes();
                        closeAll();
                    }
                }
            }, no: function () {
                if (!!opts.no)
                    opts.no();
            }
        });
    }

    function confirm(opts) {
        var index = 1;
        layer.open({
            className: 'layer-confirm-aaa',
            content: opts.msg,
            btn: opts.btns,
            shadeClose: false,
            yes: function () {
                if (index == 1) {
                    index++;
                    if (typeof opts.yes == 'function') {
                        opts.yes();
                        closeAll();
                    }
                }
            }, no: function () {
                if (!!opts.no)
                    opts.no();
            }
        });
    }

    // 关闭所有layer的弹窗
    function closeAll() {
        setTimeout("layer.closeAll()", 500);
    }

    function close(index) {
        layer.close(index);
    }

    function showLoading(show, type,index) {
        if (!!show) {
            return load();
        } else {
            close(index);
        }
    }

    // 显示加载失败
    function showError(errorMsg) {
        if (!errorMsg)
            return;
        _alert(errorMsg);
    }

    function _ajax(opts) {
        var async = true;
        if (opts.async == false) {
            async = false;
        }
        var loadType = opts.loadType || 'Page';
        var isShowLoading = (typeof opts.loadShow == 'undefined') ? true : opts.loadShow;
        var loadIndex = showLoading(isShowLoading, loadType);
        var ajaxData = {
            type: opts.type || 'POST',
            url: opts.url,
            async: async,
            data: opts.data || {},
            success: function (d) {
                _ajaxSuccess(opts, loadType, d, loadIndex);
            },
            error: function (e) {
                _ajaxError(opts, loadType, e, loadIndex);
            }
        };

        $.ajax(ajaxData);
    }

    function _ajaxSuccess(opts, loadType, d, loadIndex) {
        /* if (d.code != 0) { // 返回码错误
             if (d.code == -1) // BUSY，不显示真实错误
                 d.msg = '系统繁忙';
             var errorMsg = (!!d.msg) ? d.msg : d.code;
             if (prodConfig.config.DEBUG) {
                 errorMsg = qipanUtils.format('{0},{1}', errorMsg, opts.url);
             }
             showError(errorMsg);
         }
         else if (!!opts.success && typeof opts.success == 'function') {
             opts.success(!!qipanUtils.parseJson(d.data)?qipanUtils.parseJson(d.data):d);
         } else {
             opts.success(!!qipanUtils.parseJson(d.data) ? qipanUtils.parseJson(d.data) : d);
         }*/
        opts.success(!!utils.parseJson(d.data) ? utils.parseJson(d.data) : d);
        showLoading(false, loadType, loadIndex);
    }

    function _ajaxError(opts, loadType, e, loadIndex) {
        var _showError = function (opts, force) {
            if (force) {
                errorMsg = opts.errorMsg || '网络不给力，加载数据失败.';
                if (prodConfig.config.DEBUG)
                    errorMsg = errorMsg + opts.url;
                console.log(errorMsg);
                showError(errorMsg);
            } else if (prodConfig.config.DEBUG) {
                errorMsg = (opts.errorMsg || '网络不给力，加载数据失败.') + opts.url;
                console.log(errorMsg);
                showError(errorMsg);
            }
        };
        showLoading(false, loadType, loadIndex);
        if (!!opts.error && typeof opts.error == 'function') {

            _showError(opts, false);
            opts.error(e);
        } else
            _showError(opts, true);
    }

    //// 获取模版容器
    //function getTemplatesContainerEl() {
    //    return gEl(prodConfig.page.templateContainerId);
    //}
    //
    //// 获取body包裹元素
    //function getBodyContainerEl() {
    //    return gEl(prodConfig.page.bodyContainerId)
    //}


    // 在模版容器里添加模版
    function _addTemplate(templateName) {
        var template;
        if (!$('#' + templateName).get(0)) {
            if (!!dashanConfig.projectTemplate[templateName]) {
                template = dashanConfig.projectTemplate[templateName];
            } else {
                template = _templates[templateName];
            }
            if (!!template) {
                _getTemplatesEl().html(_getTemplatesEl().html() + template);
            }
        }
    }


    // 渲染指定id  模版名的 页面. opts.reset : 重置控件
    // opts { containerId , id / el , templateName  ,  reset , data}
    function renderTemplate(opts) {
        var $BodyContainer = getBodyContainerEl(); // 页面包裹层
        if (!!opts.id && !$('#' + opts.id).get(0)) {
            var $el = $('<div id="' + opts.id + '"></div>');
            if (!!opts.containerId) {
                gEl(opts.containerId).append($el);
            } else {
                $BodyContainer.append($el);
            }
        }

        if (!opts || !opts.templateName) {
            return;
        }
        _addTemplate(opts.templateName);
        var $container = !!opts.id ? gEl(opts.id) : $(opts.el);
        try {
            var templateHtml = template(opts.templateName, opts.data);
            $container.show();
            if (!!opts.reset) {
                $container.html(templateHtml);
            } else {
                $container.append($(templateHtml));
            }
            if (!!opts.afterRender) { // 在渲染结束后执行自定义事件
                opts.afterRender(opts.data);
            }
            //                qipanUtils.setCookie(opts.id + '_' + opts.templateName + '_' + (!!opts.param ? opts.param : ''), opts.data);
        } catch (e) {
            console.log("执行renderTemplate失败，模版渲染失败");
            console.log(e);
        }
    }


    // 跳转路由
    // 参数为路由路径path 【string】 和路由参数params 【array】
    function goRouter(path, params) {
        var pStr = '';
        if (!!params && params.length > 0) {
            for (var i = 0, len = params.length; i < len; i++) {
                pStr += ('/' + params[i]);
            }
        }
        var locationBefore = window.location.href.indexOf("#") > 0 ? window.location.href.split("#")[0] : window.location.href;
        if (path.indexOf('#') > -1) {
            window.location.href = locationBefore + path + pStr;
        } else {
            window.location.href = locationBefore + "#" + path + pStr;
        }
    }


    function renderLeftNav(id, data) {
        console.log(data);
        renderTemplate({
            id: id,
            templateName: 'templateNav',
            data: data
        });
    }

    function initLeftNav(navCode, callbackFn) {//左侧菜单
        var id = prodConfig.page.navContainerId;
        var afterNavRender = function () {
            gEl(id).find('.nav-item').removeClass("active");
            if (gEl(id).find('[data-navCode="' + navCode + '"]').get(0)) {
                gEl(id).find('[data-navCode="' + navCode + '"]').addClass("active");
            } else {
                gEl(id).find('[data-navCode="more"]').addClass("active");
            }

            renderAD(navCode,callbackFn);
        };

        var moreNavDialog;

        var initSearch = function (moreNavDialog) {
            gEl('searchBtn').off('click').on('click', function () {
                var keywords = gEl('keywordInput').val();
                close(moreNavDialog);
                goRouter('goods', ['0', 'search', keywords]);

            });
        };


        var initMoreNav = function (data) {
            gEl(id).off('click').on('click', '.nav-more', function () {
                moreNavDialog = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    shadeClose: true,
                    content: template("t_moreNavDialog", data)
                });
                initSearch(moreNavDialog);
                gEl('moreNav-dialog-closeBtn').off('click').on('click', function () {
                    close(moreNavDialog);
                })
            });
        };


        if (!gEl(id).find('.nav-item').get(0)) {
            _ajax({
                type: 'GET',
                loadShow:false,
                url: getAjaxUrl(prodConfig.ajaxApi.nav, ["pointid"], [prodCookie().getNetPoint().id]),
                success: function (data) {
                    var navData = data.result;
                    var leftNavData;
                    var navNumb = prodConfig.page.navNumb;
                    var navLen = navData.length;
                    if (navLen > navNumb) {
                        leftNavData = navData.splice(0, navNumb);
                    }
                    console.log(dataToUI.nav(leftNavData));
                    renderLeftNav(id, dataToUI.nav(leftNavData));
                    afterNavRender();
                    initMoreNav(dataToUI.nav(navData.splice(navNumb, navLen)));
                    //var navul = document.getElementById("navul");
                    //console.log(navul.children);
                    //var newnav = document.createElement("li");
                    //newnav.className = "nav-item";
                    //newnav.setAttribute('data-navCode', "64");
                    //newnav.innerHTML = "<a href=\"#goods/64\">新鲜直供</a>"
                    //navul.insertBefore(newnav, navul.children[1]);

                }, error: function (d) {
                    console.log(d)
                }
            });
        } else {
            afterNavRender();
        }
    }
    // 广告
    function renderAD(navCode, callbackFn) {
        if (!gEl('swiper-ad').get(0)) {
            _ajax({
                type: 'GET',
                loadShow: false,
                url: getAjaxUrl(prodConfig.ajaxApi.ad, ["pointid"], [prodCookie().getDefaultNetPoint()]),
                success: function (d) {
                    if (!!callbackFn) {
                        callbackFn(navCode);
                    }
                    renderTemplate({
                        id: 'ad-container',
                        templateName: 't_ad',
                        data: { data: dataToUI.ad(d.result) }
                    });
                    var Indexsw = new Swiper('#swiper-ad', {
                        pagination: '#swiper-ad .swiper-pagination',
                        nextButton: '#swiper-ad .swiper-button-next',
                        prevButton: '#swiper-ad .swiper-button-prev',
                        lazyLoading: true,
                        paginationClickable: true,
                        spaceBetween: 30,
                        centeredSlides: true,
                        autoplay: 3000,
                        loop: true,
                        autoplayDisableOnInteraction: false,
                        observer: true,//修改swiper自己或子元素时，自动初始化swiper
                        observeParents: true//修改swiper的父元素时，自动初始化swiper
                    });

                    if (dataToUI.marquee(d.result).length >= 1) {
                        renderTemplate({
                            id: 'header-ad',
                            templateName: 't_marquee',
                            data: { data: dataToUI.marquee(d.result) }
                        });
                        $("#marquee").liMarquee({
                            hoverstop: false
                        });
                    }

                }
            });

        } else {
           
            if (!!callbackFn) {
                callbackFn(navCode);
            }
        }
    }

    function restartAD() {
        if (!!prodConfig.page.adSwiper) {
            var Nsw = new Swiper('#swiper-ad', {
                pagination: '#swiper-ad .swiper-pagination',
                nextButton: '#swiper-ad .swiper-button-next',
                prevButton: '#swiper-ad .swiper-button-prev',
                lazyLoading: true,
                paginationClickable: true,
                spaceBetween: 30,
                centeredSlides: true,
                autoplay: 3000,
                autoplayDisableOnInteraction: false,
                loop: true,
                observer: true,//修改swiper自己或子元素时，自动初始化swiper
                observeParents: true//修改swiper的父元素时，自动初始化swiper

                //autoplay: prodConfig.page.adTime,
                //pagination: '#swiper-ad .swiper-pagination',
                //paginationClickable: true,
                //lazyLoading: true, //关闭预加载
                //loop: true
            });
        }
    }

    var dataToUI = (function () {
        function nav(data) {
            return {
                //  cartNum: _CD.getTotal(),getProductsTotal
                cartNum: _CD.getProductsTotal(),
                data: _.map(data, function (d) {
                    return {
                        url: '#goods/' + d.ID,
                        code: d.ID,
                        name: d.Name
                    }
                })
            }
            console.log(_CD.getProductsTotal());
        }

        function ad(data) {
            var result = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                if (d.Location == 'right') {
                    result.push({
                        img: d.Img_Url,
                        url: 'javascript:void(0)'
                    })
                }
            }
            return result;
        }

        function marquee(data) {
            var result = [];
            for (var i = 0, len = data.length; i < len; i++) {
                var d = data[i];
                if (d.Location == 'top') {
                    result.push({
                        title: d.Title,
                        url: 'javascript:void(0)'
                    })
                }
            }
            return result;
        }

        return {
            nav: nav,
            ad: ad,
            marquee: marquee
        }
    })();

    function prodCookie() {
        // 设置当前网点
        function setNetPoint(opts) {
            if (typeof opts == 'string') {
                opts = $.parseJSON(opts);
            }
            window.localStorage.setItem("netPoint", JSON.stringify(opts));
        }
        // 获取当前网点
        function getNetPoint() {
            if (!!window.localStorage.getItem("netPoint")) {
                return $.parseJSON(window.localStorage.getItem("netPoint"));
            }
            else {
                setNetPoint({
                    name: $("#netPointNameShow").attr("data-name"),
                    id: $("#netPointNameShow").attr("data-id"),
                    address: $("#netPointNameShow").attr("data-address")
                });
                return {
                    name: $("#netPointNameShow").attr("data-name"),
                    id: $("#netPointNameShow").attr("data-id"),
                    address: $("#netPointNameShow").attr("data-address")
                };
            }
        }

        // 获取默认网点
        function getDefaultNetPoint() {
            return gEl("defaultPointId").val();
        }

        // 移除记录的当前网点
        function removeNetPoint() {
            window.localStorage.removeItem("netPoint");
        }

        // 设置系统随机参数
        function setSysRan(ran) {
                window.localStorage.setItem("sysRan", ran);
        }

        function getSysRan(){
            if (!!window.localStorage.getItem("sysRan")) {
                return $.parseJSON(window.localStorage.getItem("sysRan"));
            }
            return null;
        }

        // 是否需要重置网点
        function isResetNetPoint() {
            var ran1 = utils.getLocationData('ran');
            var ran2 = getSysRan();
            if (!!ran1) {
                if (ran1 == ran2) {
                    return true;
                } else {
                    setSysRan(ran1);
                    return false;
                }
                
            }
            return true; 
        }

        function init() {
           
        }

        return {
            setNetPoint: setNetPoint,
            getNetPoint: getNetPoint,
            removeNetPoint: removeNetPoint,
            getSysRan: getSysRan,
            isResetNetPoint: isResetNetPoint,
            setSysRan: setSysRan,
            getDefaultNetPoint:getDefaultNetPoint,
            init:init
        }
    }

    function getAjaxUrl(interfaceName, queryNames, queryValues) {
        if (!queryNames) queryNames = [];
        if (!queryValues) queryValues = [];
        var url = utils.format(prodConfig.param.AJAX_BASE_URL, utils.format(interfaceName + '?{0}', utils.genQueryString(queryNames, queryValues)));

        /*if (!!loginCookie.get()) {
            if (url.indexOf('=') > -1) {
                url = url + '&token=' + qipanUtils.encodeUrl(loginCookie.get().EZToken);
            } else {
                url = url + 'token=' + qipanUtils.encodeUrl(loginCookie.get().EZToken);
            }
        }*/
        return url;
    }

    // 重载 图片
    function reloadImg(imgs) {
        if (imgs.length > 0) {
            $.each(imgs, function (i, item) {
                var $this = $(item);
                var imgSrc = $this.attr("data-src");
                var img = new Image();
                img.src = imgSrc;
                if (img.complete) {
                    $this.attr("src", imgSrc);
                } else {
                    img.onload = function () {
                        $this.attr("src", imgSrc);
                    }
                }
            })
        }
    }

    // 初始化网点显示
    function initNetPoint() {
        if (prodCookie().isResetNetPoint()) {
            $("#netPointNameShow").html(prodCookie().getNetPoint().name);
            $("#netPointAddressShow").html(prodCookie().getNetPoint().address);
        }
    }

    // 初始化系统设置
    function initSystemSetting() {
        var ran = Date.parse(new Date());
        if (!!$("#logo").get(0)) {
            document.getElementById('logo').setAttribute("href", "/?ran=" + ran);
        }
        var exitsys = function () {
            if (!window.swao) {
                return;
            }
            var version = "版本：V" + window.swao.version() + "\r\n";
            var str = prompt("退出系统？\r\n" + version + "退出密码~~~", "");
            if (str) {
                if (str == "805") {
                    window.swao.exit(0);
                }
                else if (str == "806") {
                    window.location.href = "/Home/DeviceLogin";
                }
            }
        };
        var listenToEvent = function () {
            var str = prompt("listenToEvent？", "");
            if (!str) {
                return;
            }
            if (str == "000") {
                prodCookie().removeNetPoint();
                window.location.href = "/Home/DeviceLogin";
            }
            else if (str == "111") {
                if (window.swao) {
                    window.swao.setScreenOrientationLandscape(true);
                }
                else {
                    alert('window.swao未找到！')
                }
            }
            else if (str == "222") {
                if (window.swao) {
                    window.swao.setScreenOrientationLandscape(false);
                }
                else {
                    alert('window.swao未找到！')
                }
            }
            else if (str == "test") {
                window.location.href = "/Test";
            }
            else if (str == "f5") {
                prodCookie().removeNetPoint();
            }
            else if (str == "f5f5") {
                prodCookie.removeNetPoint();
                window.location.reload();
            }
            else {
                alert('非法命令！');
            }
            //else if (str=="page") {
            //    window.location.href = "/StaticPage/listenToEvent.html";
            //}
        };
        $("#exitsys").off("click").on("click", function () {
            exitsys();
        });
        $("#listenToEvent").off("click").on("click", function () {
            listenToEvent();
        });
    }

    return {
        gEl: gEl,
        load:load,
        alert: _alert,
        dialog:dialog,
        confirm: confirm,
        closeAll: closeAll,
        close:close,
        ajax: _ajax,
        renderTemplate: renderTemplate,
        prodCookie: prodCookie,
        getAjaxUrl: getAjaxUrl,
        initLeftNav: initLeftNav,
        reloadImg: reloadImg,
        renderAD: renderAD,
        initSystemSetting: initSystemSetting,
        initNetPoint: initNetPoint,
        restartAD: restartAD
    }
});